package com.limh.readers.activity

import android.app.ProgressDialog
import android.os.Handler
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import butterknife.BindView
import butterknife.OnClick
import com.limh.readers.R
import com.limh.readers.bean.Result
import com.limh.readers.bean.User
import com.limh.readers.net.BaseRetrofit
import com.limh.readers.net.ServerApi
import com.limh.readers.utils.Utils
import com.limh.readers.utils.GsonUtils
import com.limh.readers.utils.LogUtil
import com.limh.readers.utils.SharePreferUtils
import rx.schedulers.Schedulers

/**
 * Function:
 * author: limh
 * time:2017/7/21
 */

class LoginActivity : BaseActivity() {

    @BindView(R.id.edit_email)
    lateinit var editEmail: EditText
    @BindView(R.id.edit_pass1)
    lateinit var editPass1: EditText

    lateinit var dialog: ProgressDialog

    private val TAG: String = "LoginActivity"

    override fun findView() {
        setContentView(R.layout.activity_login)
    }

    override fun initViews() {
    }

    override fun initDatas() {
        editPass1.setOnClickListener {}
    }


    @OnClick(R.id.image_back, R.id.btn_login, R.id.txt_forget, R.id.txt_regiter)
    fun OnClick(view: View) {
        when (view.id) {
            R.id.image_back -> finish()
            R.id.btn_login -> login()
            R.id.txt_regiter -> openActivity(RegterActivity::class.java)
        }
    }

    override fun onResume() {
        super.onResume()
        if ("" != SharePreferUtils.get(this, "user", "")) {
            val user = GsonUtils.str2Bean(SharePreferUtils.get(this, "user", "") as String, User::class.java)
            try {
                editEmail.setText(user.email)
                editPass1.setText(user.password)
            } catch (e: NullPointerException) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 登录
     */
    private fun login() {

        if (TextUtils.isEmpty(editEmail.text)) {
            showToastShort("邮箱或昵称不能为空")
            return
        }
        if (TextUtils.isEmpty(editPass1.text)) {
            showToastShort("密码不能为空")
            return
        }
        val params: Map<String, String>
        if (Utils.isEmail(editEmail.text.toString())) {
            params = mapOf(Pair("email", editEmail.text.toString()), Pair("password", editPass1.text.toString()))
        } else {
            params = mapOf(Pair("username", editEmail.text.toString()), Pair("password", editPass1.text.toString()))
        }


        dialog = ProgressDialog(this)
        dialog.setMessage("正在登录，请稍后...")
        dialog.show()

        LogUtil.i(TAG, params.toString())
        val service: ServerApi = BaseRetrofit().createService(ServerApi::class.java)
        service.login(params)
                .subscribeOn(Schedulers.newThread())
                .subscribeOn(Schedulers.io())
                .subscribe({ response ->
                    LogUtil.i(TAG, response.toString())
                    when (response.getCode()) {
                        200 -> sendMsg(GsonUtils.Gson2Str(response), 0x123, handler)
                        else -> sendMsg(response.getMessage(), 0x124, handler)
                    }
                }, { t ->
                    sendMsg("网络异常", 0x124, handler)
                    LogUtil.d(TAG, t.toString())
                })
    }

    /**
     * 消息处理
     */
    private val handler = Handler(Handler.Callback { msg ->
        when (msg.what) {
            0x123 -> {
                val rep: Result = GsonUtils.str2Bean(msg.data.getString("msg"), Result::class.java)
                openActivity(MainActivity::class.java)
                finish()
                LogUtil.w(TAG, "登陆保存=" + rep.getData())
                SharePreferUtils.put(this, "user", rep.getData().toString())
                showToastShort(rep.getMessage())
            }
            else -> {
                showToastShort(msg.data.getString("msg"))
            }
        }
        if (dialog.isShowing) dialog.dismiss()
        false
    })
}